﻿#include "DialogWaveformAnalysis.h"
#include "ui_DialogWaveformAnalysis.h"

#include "AnimationSettingData.h"
#include "DataChosenListDialog.h"
#include <QIntValidator>
#include "IdaWidgetHelper.h"
#include "BaseWidget/IdaDialogMsg.h"
#include <QListView>
#include <QDebug>

#include "BaseModule/IBaseSignal.h"

namespace pst
{
    DialogWaveformAnalysis::DialogWaveformAnalysis(QWidget* parent)
        : IdaDialogFrame(parent), ui(new Ui::DialogWaveformAnalysis())
    {
        ui->setupUi(this);

        setWindowTitle(tr("波形分析"));
        IdaWidgetHelperInstance->setMainButtonStyle(ui->pushButton_confirm); // 将确定设置为主按钮

        ui->pushButton_Curve->setIcon(QIcon(":/rc/apostrophe.png"));
        ui->pushButton_Curve->setStyleSheet("QPushButton { text-align: center; }");

        ui->label_FilterOrder->setText(QStringLiteral("滤波实际阶数\n(仅支持正偶数阶)"));
    }

    DialogWaveformAnalysis::~DialogWaveformAnalysis()
    {
        delete ui;
    }

    void DialogWaveformAnalysis::setCurveNameList(const QList<QString>& curveNameList)
    {
        m_curveNameList = curveNameList;
        m_model.setStringList(m_curveNameList);
        updateValueRange();
    }

    void DialogWaveformAnalysis::setInit(QStringList& params)
    {
        if (params.at(0) != "5")
            return;
        params.removeFirst();
        ui->doubleSpinBox_Frequency->setValue(params.at(1).toDouble());
        if (params.at(2) == "low")
            ui->comboBox_FilterType->setCurrentIndex(0);
        else
            ui->comboBox_FilterType->setCurrentIndex(1);
        ui->spinBox_FilterOrder->setValue(params.at(3).toInt());
        bool ok = false;
        auto pa4 = params.at(4).toDouble(&ok);
        if (ok&& !std::isnan(pa4))
        {
            ui->lineEdit_TimeDomainLeft->setText(params.at(4));
        }
        auto pa5 =params.at(5).toDouble(&ok);
        if (ok&&!std::isnan(pa5))
        {
            ui->lineEdit_TimeDomainRight->setText(params.at(5));
        }
        slot_sentChosenDataIds(createSelectedIndexes(QStringList() << params.front()));
    }

    void DialogWaveformAnalysis::updateValueRange()
    {
        // 设置变量起始值和终止值
        //  待处理
        m_minValue = 0.001;
        m_maxValue = 999999999.999;

        QDoubleValidator* doubleValidator = new QDoubleValidator(m_minValue, m_maxValue, 3, this);
        doubleValidator->setNotation(QDoubleValidator::StandardNotation);
        ui->lineEdit_TimeDomainLeft->setValidator(doubleValidator);
        ui->lineEdit_TimeDomainRight->setValidator(doubleValidator);
    }

    void DialogWaveformAnalysis::on_pushButton_confirm_clicked()
    {
        QSignalBlocker blocker(ui->pushButton_confirm); 
        // 点确定后首先做错误判断
        auto _isOK = AbnormalErrorJudgment();
        if (!_isOK)
        {
            blocker.unblock();
            return;
        }
        // 在此之后做数据处理

        QString filterType;
        if (ui->comboBox_FilterType->currentIndex() == 0)
        {
            filterType = "low";
        }
        else
        {
            filterType = "high";
        }


        emit bool isSuc = signal_sendAnalysisData(m_curveNameList.at(m_selectedIndexs.first()), ui->doubleSpinBox_Frequency->value(), filterType, ui->spinBox_FilterOrder->value(), m_TimeDomainLeftValue, m_TimeDomainRightValue,-1,QString(), false);
        blocker.unblock();
        if (!isSuc)
        {
            return;
        }
        //QString _pyCode = QString("PostProcessing.lineChartDialogWaveformAnalysis('%1',%2,'%3',%4,'%5','%6')")
        //                      .arg(m_curveNameList.at(m_selectedIndexs.first()))
        //                      .arg(ui->doubleSpinBox_Frequency->value())
        //                      .arg(filterType)
        //                      .arg(ui->spinBox_FilterOrder->value())
        //                      .arg(std::isnan(m_TimeDomainLeftValue)?QString("nan"):QString::number(m_TimeDomainLeftValue))
        //                      .arg(std::isnan(m_TimeDomainRightValue)?QString("nan"):QString::number(m_TimeDomainRightValue));
        //emit IBaseSignalInstance->signal_execPYCode(QStringList{_pyCode}, true, false);


        IdaDialogFrame::accept();
    }

    void DialogWaveformAnalysis::on_pushButton_cancel_clicked()
    {
        this->close();
    }

    void DialogWaveformAnalysis::slot_sentChosenDataIds(const QModelIndexList& chosenID)
    {
        m_selectedIndexs.clear();
        auto count = chosenID.count();
        QString strText{};
        for (int i = 0; i < count; ++i)
        {
            auto chosenData = chosenID.at(i);
            if (chosenData.isValid())
            {
                auto str = chosenData.data().toString();
                strText += str + "\n";

                auto index = chosenID.at(i).row();
                m_selectedIndexs.append(index);
            }
        }
        if (!m_selectedIndexs.isEmpty())
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_Curve, true, Qt::blue);
        else
            IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_Curve, false, Qt::white);
    }

    void DialogWaveformAnalysis::on_pushButton_Curve_clicked()
    {
        m_dataChosenListDialog = new DataChosenListDialog();
        m_dataChosenListDialog->setFixedSize(300, 280);
        // m_dataChosenListDialog->moveToCenter();
        m_dataChosenListDialog->setData(m_curveNameList);
        m_dataChosenListDialog->setMultipleSelected(false);
        m_dataChosenListDialog->updateUI();
        m_dataChosenListDialog->showWindow();
        if (m_selectedIndexs.isEmpty() && m_curveNameList.isEmpty() == false) // 默认选中第一个
            m_selectedIndexs.append(0);
        m_dataChosenListDialog->setSelctedIndexs(m_selectedIndexs);
        IdaWidgetHelperInstance->setPushButtonSelcetBarCheckedState(ui->pushButton_Curve, true, Qt::blue); // 因为有默认选项

        connect(m_dataChosenListDialog,
                &DataChosenListDialog::signal_sentChosenDataIds,
                this, &DialogWaveformAnalysis::slot_sentChosenDataIds);
    }

    bool DialogWaveformAnalysis::AbnormalErrorJudgment()
    {
        // 判断1-曲线不能为空
        if (m_selectedIndexs.isEmpty())
        {
            auto _text = QString("未识别到有效曲线，请选择待处理的波形曲线。");
            auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
            return false;
        }

        // 判断2-截止频率
        // auto _value = ui->doubleSpinBox_Frequency->();
        // if (_value)//待处理
        //{
        //     auto _text = QString("截止频率需在0<Wn<fs/2范围内！");
        //     auto _res = IdaDialogMsg::showDialog(nullptr, _text, EDialogMsg::Warning, QStringLiteral("警告"), {QStringLiteral("确定")});
        //     return false;
        // }

        // 判断3-时域定义
        if (ui->lineEdit_TimeDomainLeft->text().isEmpty())
        {
            m_TimeDomainLeftValue = std::numeric_limits<double>::quiet_NaN();
        }
        else
        {
            m_TimeDomainLeftValue = ui->lineEdit_TimeDomainLeft->text().toDouble();
        }
        if (ui->lineEdit_TimeDomainRight->text().isEmpty())
        {
            m_TimeDomainRightValue = std::numeric_limits<double>::quiet_NaN();
        }
        else
        {
            m_TimeDomainRightValue = ui->lineEdit_TimeDomainRight->text().toDouble();
        }

        return true;
    }

    QModelIndexList DialogWaveformAnalysis::createSelectedIndexes(const QStringList& params) {
        QModelIndexList selectedIndexes;

        foreach(const QString & param, params) {
            int row = m_curveNameList.indexOf(param);
            if (row != -1) {
                // 使用成员模型m_model创建索引，确保索引与模型生命周期一致
                QModelIndex index = m_model.index(row, 0);
                if (index.isValid()) {
                    selectedIndexes.append(index);
                }
            }
        }
        return selectedIndexes;
    }

} // namespace pst
